// pages/integral/order-confirm/order-confirm.ts
import { createIntegralOrder } from '../../../api/points_mall.js';
import { PAGES, goToPage } from '../../../config/pages.js';

Page({
  data: {
    orderData: {},
    addressList: [],
    selectedAddress: null,
    remark: '',
    loading: false
  },

  onLoad(options: any) {
    if (options.data) {
      const data = JSON.parse(decodeURIComponent(options.data));
      this.setData({ orderData: data });
      this.getAddressList();
    }
  },

  // 获取地址列表
  async getAddressList() {
    try {
      // 这里应该调用获取地址列表的API
      // const res = await getAddressList();
      // 暂时使用模拟数据
      const mockAddresses = [
        {
          id: 1,
          real_name: '张三',
          phone: '13800138000',
          province: '北京市',
          city: '北京市',
          district: '朝阳区',
          detail: 'xxx街道xxx号',
          is_default: 1
        }
      ];
      
      this.setData({
        addressList: mockAddresses,
        selectedAddress: mockAddresses.find(item => item.is_default) || mockAddresses[0]
      });
    } catch (error) {
      console.error('获取地址列表失败:', error);
      wx.showToast({
        title: '获取地址失败',
        icon: 'none',
      });
    }
  },

  // 选择地址
  onSelectAddress() {
    wx.navigateTo({
      url: '/pages/user/address/list?select=true',
      events: {
        selectAddress: (address: any) => {
          this.setData({ selectedAddress: address });
        }
      }
    });
  },

  // 备注输入
  onRemarkInput(e: any) {
    this.setData({ remark: e.detail.value });
  },

  // 提交订单
  async onSubmitOrder() {
    if (!this.data.selectedAddress) {
      wx.showToast({
        title: '请选择收货地址',
        icon: 'none',
      });
      return;
    }

    if (this.data.loading) return;

    try {
      this.setData({ loading: true });
      wx.showLoading({ title: '创建订单中...' });
      
      const res = await createIntegralOrder({
        addressId: this.data.selectedAddress.id,
        mark: this.data.remark,
        unique: this.data.orderData.product.unique,
        num: this.data.orderData.num
      });

      wx.hideLoading();
      wx.showToast({
        title: '订单创建成功',
        icon: 'success',
      });
      
      setTimeout(() => {
        wx.redirectTo({
          url: `/pages/integral/order-detail/order-detail?orderId=${res.data.orderId}`
        });
      }, 1500);
    } catch (error) {
      console.error('创建订单失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: error.message || '创建订单失败',
        icon: 'none',
      });
    } finally {
      this.setData({ loading: false });
    }
  }
});
